#!/usr/bin/python
'''
community2clusters.py:
	input: tree output from community and map file generated if the graph
				need to be convereted for community
	output: clusters files to use with addClusterLabels.py

	As a side note, communities pushes all node numbers down such that the
	lowest is 0 and they are consecutive.

usage:
	community2clusters.py input map > output
		all arguments are filenames

Created on May 1, 2011
@author: ncrowell
'''

import sys

def processInput(f):
	# Tree input is a hierarchy of clusters starting with the most number
	#   of clusters and ending with just two clusters. 
	# For now this function returns the processed hierarchy
	# Each cluster stored as a list in a dictionary keyed by the cluster name
	ret = []
	clusters = dict()
	prevlevel = -1

	line = f.readline()
	s = line.split()
	v = s[0]
	c = s[1]
	clusters[c] = [v]

	for line in f.readlines():	
		s = line.split()
		v = s[0]
		c = s[1]
		# check for next level
		if ( v == '0' ):
			ret.append(clusters)
			clusters = dict()
			prevlevel = prevlevel + 1
		if ( prevlevel == -1 ):
			if ( clusters.has_key(c) ):
				clusters[c].append(v)		
			else:
				clusters[c] = [v]
		else: # v is a ref to a cluster at the prev level
			cluster = ret[prevlevel][v]
			if ( clusters.has_key(c) ):
				clusters[c].extend(cluster)
			else:
				clusters[c] = cluster[:] # copy
	# append last set of clusters -- this might actually be unnecessary
	ret.append(clusters)
	return ret

def processMapfile(f):
	ret = dict()
	for line in f.readlines():	
		s = line.split()
		ret[s[0]] = s[1]
	return ret

def genOutput(clusters, f, mapback):
	for k in clusters.keys():
		f.write(k + ":")
		for v in clusters[k]:
			f.write(" " + mapback[v])
		f.write("\n")

def main():
	if ( len(sys.argv) != 4 ): 
		print("usage:\n"+
					"  community2clusters.py tree map  k > output\n"+
					"    input: tree output from community and mapback file that was generated\n" +
					"      by convertGraph_community and the hierarchy level to use\n"+
					"  output: commuities relative to original node names\n")
		sys.exit()	

	inputfile = file(sys.argv[1], 'r')
	mapfile = file(sys.argv[2], 'r')
	k = int(sys.argv[3])
	outputfile = sys.stdout
	

	# process edge list
	clusters = processInput(inputfile)
	inputfile.close()

	# generte map back
	mapback = processMapfile(mapfile)

	# genereate dot file from graph list
	genOutput(clusters[k], outputfile, mapback)



if __name__ == '__main__':
	main()
